<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
/**
 * Mrp
 *
 * @icon fa fa-circle-o
 */
class Mrps extends Backend
{

    /**
     * Mrps模型对象
     * @var \app\admin\model\kuyou\Mrps
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuyou\Mrps;
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->column('name');
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('ids',$ids);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //获取设置
                $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
                $setList = [];
                foreach ($set as $set_k=>$set_v){
                    if(!empty($set_v['set'])){
                        $set_v['set'] = unserialize($set_v['set']);
                    }
                    $setList[$set_v['name']] = $set_v;
                }
                //数量价格格式化
                $number_decimal = $setList['number_decimal']['value'];

                $params = $this->preExcludeFields($params);
                $plan = Db::name('kuyou_plan')->where(['purchase_code'=>$params['purchase_code']])->find();

                $info = Db::name('kuyou_plan_info')->where(['id'=>['in',$params['info_id']]])->select();
                $data = [];
                foreach ($info as $info_k=>$info_v){
                    $bom = Db::name('kuyou_bom')->where(['goods_code'=>$info_v['goods_code']])->column('id');
                    $info_id = Db::name('kuyou_bom_info')->where(['bom_id'=>['in',$bom]])->select();
                    foreach ($info_id as $info_id_k=>$info_id_v){
                        $info_id_v['number'] = $info_id_v['number']*$info_v['number'];
                        $info_id_v['basic_nmber'] = $info_id_v['basic_nmber']*$info_v['number'];
                        $info_id_v['money'] = $info_id_v['money']*$info_v['number'];
                        $stock = Db::name('kuyou_goods_stock')->where(['goods_code'=>$info_id_v['goods_code']])->sum('stock');
                        $buy_number = 0;
                        if($stock<$info_id_v['basic_nmber'] && $info_id_v['number']==$info_id_v['basic_nmber']){
                            $buy_number = round($info_id_v['number']-$stock,$number_decimal);
                        }else if($stock<$info_id_v['basic_nmber'] && $info_id_v['number']!=$info_id_v['basic_nmber']){
                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$info_id_v['goods_code']])
                                ->field('goods_type_id,goods_code,goods_name,goods_specification_id,note,unit_id,more_unit,goods_barcode')
                                ->find();;
                            $unit = Db::name('kuyou_unit')->where((new Goods())->setWhere(['id'=>$goods['unit_id']]))->field('id,name')->find();
                            $advance_rate = Db::name('kuyou_unit_conversion')->alias('uc')
                                ->join('kuyou_unit u','u.id=uc.vice_unit')
                                ->where(['uc.main_unit'=>$unit['id'],'uc.vice_unit'=>$info_id_v['unit_id']])
                                ->value('advance_rate');
                            if($advance_rate){
                                $stock = round($stock/$advance_rate,$number_decimal);
                                $buy_number = round($info_id_v['number']-$stock,$number_decimal);
                            }
                        }
                        $data[] = [
                            'goods_id' => $info_id_v['goods_id'],
                            'goods_code' => $info_id_v['goods_code'],
                            'goods_name' => $info_id_v['goods_name'],
                            'goods_note' => $info_id_v['goods_note'],
                            'unit_id' => $info_id_v['unit_id'],
                            'default_unit' => $info_id_v['default_unit'],
                            'purchase' => $info_id_v['purchase'],
                            'number' => $info_id_v['number'],
                            'basic_nmber' => $info_id_v['basic_nmber'],
                            'stock' => $stock,
                            'buy_number' => $buy_number,
                            'money' => $info_id_v['money'],
                            'remark' => $info_id_v['remark'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }

                if($plan){
                    unset($plan['id']);
                    $plan['createtime'] = time();
                    $plan['updatetime'] = time();
                }else {
                    $this->error(__('No rows were inserted'));
                }
                $result = false;
                Db::startTrans();
                try {
                    if(!empty($plan)){
                        $result = $this->model->insertGetId($plan);
                        foreach ($data as $data_k=>$data_v){
                            $data[$data_k]['plan_id'] = $result;
                        }
                        Db::name('kuyou_mrp_info')->insertAll($data);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success(__('Added successfully'));
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isAjax()) {
            $data = input();
            $id = isset($data['id'])?$data['id']:'';
            if(empty($id)){
                $info = [];
            }else{
                $info = Db::name('kuyou_mrp_info')->where(['plan_id'=>$id])->select();
                foreach ($info as $info_k=>$info_v){
                    $info[$info_k]['unit'] = Db::name('kuyou_unit')->where(['id'=>$info_v['unit_id']])->find();
                }
            }
            $result = array("total" => sizeof($info), "rows" => $info);
            return json($result);
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::name('kuyou_mrp_info')->where(['plan_id'=>$v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //审核/反审核
    public function examine($ids = null,$examine=1){
        $examine_set= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if(empty($ids)){
            if($examine_set!=1){
                return ['status'=>0,'msg'=>__('System error')];
            }
            $this->error(__('Please select the data to be operated on'));
        }
        $admin = Session::get('admin');
        if($examine==1){
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                    ->update(['examine_status'=>1,'examine_id'=>$admin['id'],'examine_time'=>time(),'operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data review was successful'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Audit failed'));
            }
        }else{
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
            if(empty($list)){
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Please select the data that needs to be de audited'));
            }
//            foreach ($list as $list_k=>$list_v){
//                $purchase_id = Db::name('kuyou_goods_excpur')->where(['purchase_id'=>$list_v['id']])->column('exchange_id');
//                if(!empty($purchase_id)){
//                    if($examine_set!=1){
//                        return ['status'=>0,'msg'=>__('Cannot manipulate data of generated production orders')];
//                    }
//                    $this->error(__('Cannot reverse audit data of generated production orders'));
//                }
//            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                    ->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>__('Operation successful')];
                }
                $this->success(sizeof($list).__('The data has been successfully de audited'));
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>__('operation failed')];
                }
                $this->error(__('Anti audit failed'));
            }
        }
    }

    public function setdata(){
        $params = $this->request->post("row/a");
        if ($params) {
            if($params[0]){
                $params = json_decode($params[0],true);
            }else{
                $params = [];
            }
            if(empty($params)){
                $this->error(__('Parameter error'));
            }else{
                Session::set('GoodsPurchaseOrder',serialize($params));
                $this->success();
            }
        }
    }
}
